package org.geekbang.thinking.in.spring.ioc.dependency.injection.fieldinjection;

import org.geekbang.thinking.in.spring.ioc.dependency.injection.UserHolder;
import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * 基于 Java 注解的 依赖字段 注入示例
 *
 * @author wangyh2
 * @version v1.0
 * @since 2021-09-25 09:32
 */
public class AnnotationDependencyFieldInjectionDemo {

    @Autowired
    private User user;
    @Autowired
    private User superUser;

    @Autowired
    private UserHolder userHolder;
    @Resource
    private UserHolder userHolder2;


    public static void main(String[] args) {
        // 1、创建 BeanFactory 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 2、注册 Configuration Class（配置类）
        applicationContext.register(AnnotationDependencyFieldInjectionDemo.class);
        // 3、加载 XML 资源，解析并且生成 BeanDefinition
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);
        String xmlResourcePath = "classpath:/META-INF/dependency-lookup-context.xml";
        xmlBeanDefinitionReader.loadBeanDefinitions(xmlResourcePath);
        // 4、启动 Spring 应用上下文
        applicationContext.refresh();
        // 5、依赖查找 AnnotationDependencyFieldInjectionDemo Bean
        AnnotationDependencyFieldInjectionDemo demo = applicationContext.getBean(AnnotationDependencyFieldInjectionDemo.class);
        // @Autowired 字段关联
        System.out.println(demo.userHolder);
        System.out.println(demo.userHolder2);
        System.out.println(demo.userHolder == demo.userHolder2);

        System.out.println(demo.user);
        System.out.println(demo.superUser);


        // 6、显示地关闭 Spring 应用上下文
        applicationContext.close();
    }

    @Bean
    public UserHolder userHolder(User user) {
        return new UserHolder(user);
    }
}
